// JavaScript Document
function test() {
    testBiBao();
}

var testRegExp = function() {
    var reg = new RegExp('[^hi\b.*$]');
    var testStr = 'hidfsfasdf';
    console.log(reg.test(testStr));
};
var testTrim = function() {
    var str = '         sdsdfsdf         ';
    console.log(str);

    str = jQuery.trim(str);
    console.log(str);
};
var testBiBao = function() {
    var f = function(a) {
        return function(a) {
            return ++a;
        };
    };
    var b = f(1)();
    console.log(b);
};
///继承

// Array.method

var mammal = function(spec) {
    var that = {};
    that.get_name = function() {
        return spec.name || '';
    };
    that.saying = function() {
        return spec.saying || '';
    };
    return that;
};
var cat = function(spec) {
    spec.saying = spec.saying || 'miao';
    var that = mammal(spec);
    that.get_name = function() {
        return spec.name || '';
    };
    return that;
};
var coolcat = function(spec) {
    var that = cat(spec), super_get_name = that.superior('get_name');
    that.get_name = function() {
        return 'like' + super_get_name() + 'baby';
    };
    return that;
};
//继承over
var t = function(id) {
    //var node = $F('w');
    //var level = 1;
    var step = function() {
        var hex = 20;
        //level.toString(16);
        //node.style.backgroundColor = '#ffff' + hex + hex;
        var w = $('#' + id).window('options').width;
        var h = $('#' + id).window('options').height;
        $('#' + id).window('resize', {
            width : w + 50,
            height : h + 30
        });
        $('#' + id).window('center');
        if (w < 1000) {
            //level++;
            setTimeout(step, 5);
        }
    };
    setTimeout(step, 5);
};

/**
 * 简单的文件的保存是保存在 localstorage.只有在进行导出操作的时候才能保存为DSC的文件
 */
function initFiles() {
    var files = $F('files');
    if (files) {
        var items = $C("ui");
        var root = {
            text : 'files',
            children : []
        };
        items.setAttribute("class", "easyui-tree");
        items.setAttribute("id", 'ff');
        files.appendChild(items);

        var msgHandle = function() {
            var message = arguments[0];
            var files = message.split('&');
            // localStorage.clear();
            //		for(var i in localStorage){
            //			var data = {id:root.children.length,text:i};
            //			root.children.push(data);
            //		}
            for (var i in files) {
                var file = files[i];
                if (file == '') {
                    continue;
                }
                var data = {
                    id : i,
                    text : file
                };
                root.children.push(data);
            }
            $('#ff').tree({
                data : [root],
                iconCls : "icon-folder",
                lines : true,
                animate : true,
                onClick : function(node) {
                    var presenterName = node.text;
                    if (presenterName != 'files') {
                        openLocalFile(presenterName);
                    }
                },
                onContextMenu : function(e, node) {
                    e.preventDefault();
                    // select the node
                    $('#ff').tree('select', node.target);
                    // display context menu
                    $('#fm').menu('show', {
                        left : e.pageX,
                        top : e.pageY
                    });
                }
            });
        };
        connectSaveServer("files", {}, msgHandle);
    }

}

function removefile() {
    var node = $('#ff').tree('getSelected');
    if (node) {
        var tab = $('#canvasTabs').tabs('getTab', node.text);
        if (tab) {
            $('#canvasTabs').tabs('close', node.text);
        }
        $('#ff').tree('remove', node.target);
        localStorage.removeItem(node.text);
    }
}

function openLocalFile(presenterName) {
    var content;
    content = localStorage.getItem(presenterName);
    //  content = '{"complete":{"sys":[{"name":"new","type":"Work","property":{"hasShadow":"yes,no;null","staticCnt":"null"},"showInfo":{"rectangle":{"x":333,"y":57,"w":157,"h":92},"color":"black","visible":"yes,no;yes","showContent":"yes,no;yes","showLabel":"yes,no;yes"},"content":{"composite":{"exitPoint":[{"name":"and","showInfo":{"x":412,"y":81}}]}}}]}}';
    console.log(content);
    if (content) {
        openf(presenterName, content);
    } else {
        var file = presenterName + '.dsc';
        var msgHandle = function() {
            console.log(arguments[0]);
            openf(presenterName, arguments[0]);
            localStorage.setItem(presenterName, arguments[0]);
        };
        connectSaveServer('open', file, msgHandle);
    }

}

function openf(presenterName, content) {
    var tab = $('#canvasTabs').tabs('getTab', presenterName);
    if (tab) {
        $('#canvasTabs').tabs('select', presenterName);
    } else {
        var canvas = _dss_editor._canvas._operation.buildTab(presenterName, _dss_editor._canvas._type.VIEW);
        // var canvas = buildWindow(presenterName, CANVAS_VIEW);
        var sysForView = JSON.parse(content);
        canvas.init(sysForView);
        canvas.matchSize();
        canvas.update();
    }
}

function connectSaveServer(location, sendMsg, msgHandle) {
    try {
        var url = "ws://127.0.0.1:8080/" + location;
        var ws = new WebSocket(url);
        ws.onopen = function() {
            this.send(sendMsg);
        };
        ws.onmessage = function(message) {
            msgHandle(message.data);
        };
        ws.onclose = function() {
        };

    } catch (exc) {
        console.error(exc.stack);
    }
}

function addFile(fileName) {
    var root = $('#ff').tree('getRoot');
    //	var id = localStorage.length-1;
    $('#ff').tree('append', {
        parent : root.target,
        data : [{/*id:id,*/
            text : fileName
        }]
    });

}

function localSave(presenterName, content) {
    //localStorage.
    localStorage.setItem(presenterName, content);
    var msgHandle = function() {
    };
    //connectSaveServer('save', content, msgHandle);
}

function stringifyToLocalSaveMessage(canvas) {
    var msg = '{';
    msg += '"presenterName":"' + canvas.presenterName + '",';
    msg += _dss_editor._toolkit.stringifySysForViewToJSON(canvas.baseSysForView);
    msg += '}';
    console.log(msg);
    // JSON.parse(msg);
    //	 msg = '##' + msg.length + msg;

    return msg;
}

//测试用
function createMyHome() {
    var content = localStorage.getItem('MyHome');
    var canvas = _dss_editor._canvas._operation.buildTab('MyHome', _dss_editor._canvas._type.VIEW);
    // var canvas = buildWindow(presenterName, CANVAS_VIEW);
    var sysForView = content || {
        complete : {
            sys : {},
            links : []
        }
    };
    console.log(content);
    if (content) {
        sysForView = JSON.parse(content);
    }

    canvas.init(sysForView);
    canvas.matchSize();
    canvas.update();
}

function openCmdCtrl() {
    var ctrl = $('#cmdctrl').attr('ctrl');
    if (ctrl === 'open') {
        $('#cmdctrl').html('⋀');
        $('#cmdctrl').attr('ctrl', 'close');
       // $('#command').width(100);
    } else if (ctrl === 'close') {
        $('#cmdctrl').html('⋁');
        $('#cmdctrl').attr('ctrl', 'open');
    }
    $('#command').toggle('fast');
    setHeight();

}

function setHeight() {
    var c = $('#content');
    var p = c.layout('panel', 'north');
    var oldHeight = p.panel('panel').outerHeight();
    p.panel('resize', {
        height : 'auto'
    });
    var newHeight = p.panel('panel').outerHeight();    
    newHeight = c.height() + newHeight - oldHeight > 40?c.height() + newHeight - oldHeight:40;
    c.height(newHeight);
    c.layout('resize');
}
